package com.swordxu.yim.server.packet;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.swordxu.yim.server.packet.base.DefaultHeader;
import com.swordxu.yim.server.packet.base.Header;
import com.swordxu.yim.server.packet.base.Packet;
import com.swordxu.yim.server.dbproxy.model.User;
import com.swordxu.yim.server.utils.ProtocolConstant;

/**
 * 请求/返回 登录服务器数据包
 * Created by 徐晓明 on 2015/1/6.
 */
public class LoginPacket extends Packet {
    /**
     * 登录服务器数据包封包
     * @return
     */
    @Override
    public String encode() {
        Header header = mResponse.getHeader();
        PacketResponse res = (PacketResponse) mResponse;
        JSONObject jo = new JSONObject();
        jo.put("header", header);
        jo.put("body", res.getUser().toJson());
        return jo.toJSONString();
    }

    /**
     * Loginserver数据包解包
     */
    @Override
    public void decode(String buffer) {
        PacketRequest rq = new PacketRequest();
        Header header = new Header();
        JSONObject jo = JSON.parseObject(buffer);
        header = jo.getObject("header", Header.class);
        rq.setHeader(header);
        rq.entity = JSON.parseObject(jo.getString("body"), rq.entity.getClass());
        this.mRequest = rq;
    }

    /**
     * 请求数据包
     */
    public static class PacketRequest extends Request {
        public static class Entity{
            public String name;
            public String pwd;
            public int clientType;
        }

        public Entity entity = new Entity();
    }

    /**
     * 响应数据包
     */
    public static class PacketResponse extends Response {
        public static class Entity{
            public int serverTime;
            public int result;
            public int onlineStatus;
            public String name;
            public String userId;
            public String nickName;
            public String avatarUrl;
            public String tile;
            public String position;
            public int roleStatus;
            public int sex;
            public String departId;
            public int jobNUm;
            public String telphone;
            public String email;
            public String token;
            public int userType;
        }

        public void setUser(User user) {
            this.user = user;
        }

        public User getUser() {
            return this.user;
        }

        public PacketResponse(Entity entity) {
            this.entity = entity;
            Header header = new DefaultHeader(ProtocolConstant.SID_LOGIN, ProtocolConstant.CID_LOGIN_RES_USERLOGIN);
            setHeader(header);
        }
        public Entity entity;
        User user = new User();
    }
}
